/*
 * @Author: wfl
 * @LastEditors: wfl
 * @description: 
 * @updateInfo: 
 * @Date: 2020-12-08 13:56:54
 * @LastEditTime: 2021-03-19 15:28:03
 */
import getFileChunkMd5 from './getFileMd5'
// 切片大小 2M
export let CHUNK_SIZE = 2 * 1024 * 1024;
export interface FileBlob {
    file: Blob;
    type?: String
}

export interface IChunkData {
    fileHash: string
    fileMd5No: string
    chunk: Blob,
    percentage?: number
    type?: string
}

export default class BreakPointLoad {
    // 切片数据 
    private fileChunkList!: any[];
    // 文件md5
    private fileMd5Data: any = '';
    // 最终数据
    private chunkData: any = []
    // 文件类型
    private type: string = ''
    // 获取上传文件  size字节,例：切片大小为1M则size= 1 * 1024 * 1024
    async inputChange(file: any, cb: Function, size?: number) {
        // 若传入切片大小，则按照传入切片大小切片
        if (size) {
            CHUNK_SIZE = size
        }
        this.type = file.type
        const name = file.name;
        if (file) {
            this.fileChunkList = await this.createFileChunk(file, (data: IChunkData, size: number)=>{
                cb(data, size);
            });
            this.fileMd5Data = await getFileChunkMd5(this.fileChunkList)
            this.chunkData = this.fileChunkList.map(({ file }: { file: Blob }, index: Number) => ({
                // 文件名
                name: name,
                // 文件类型
                type: this.type,
                // 文件md5
                fileHash: this.fileMd5Data,
                // 切片标记
                fileMd5No: `${this.fileMd5Data}-${index}`,
                // 切片文件
                chunk: file,
                // 上传进度
                percentage: 0
            }));
            return this.chunkData
        }
    }
    // 文件切片
    async createFileChunk(file: any, cb: Function): Promise<FileBlob[]> {
        const list: FileBlob[] = [];
        const type = this.type;
        // 切片位置
        let ssize = 0;
        let len = await Math.ceil(file.size / CHUNK_SIZE)
        while (ssize < file.size) {
            const data = {
                file: file.slice(ssize, ssize + CHUNK_SIZE),
                type: type
            };
            list.push(data)
            ssize += CHUNK_SIZE;
            cb(list, len)
        }
        return await list;
    }
}